package com.tbit.main.controller;


import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.MapConstant;
import com.tbit.main.constant.SysConstant;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.AccountUser;
import com.tbit.main.pojo.Geo;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 电子围栏
 *
 * @author Leon
 * 2019年1月23日 下午3:51:50
 */
@RestController
@RequestMapping("/geo")
public class GeoController {
    @Autowired
    private GeoService geoService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AccountUserService accountUserService;

    /**
     * 根据代理商id查询
     */
    @RequestMapping("/getByAccountId")
    public JsonResult send(String token, Integer accountId, Integer mapType) {
        AccountUser accountUserToken = tokenService.getAccount(token);
        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }

        /**触发删除用户检测*/
        AccountUser accountUserDB = accountUserService.getById(accountUserToken.getAccountUserId());
        if (accountUserDB == null) {
            /**删除token*/
            redisService.del(token);
            throw new BaseException("AccountUser.notExist");
        }

        Geo geo = null;
        List<Geo> geos = geoService.getByAccountId(accountId);

        if (geos.size() > 0) {
            geo = geos.get(0);
            /**校准*/
            calibrateService.calGeo(geo, MapConstant.MAP_ORI, mapType);
        }

        return JsonResult.succ(geo);
    }

    //获取运营区域
    @RequestMapping("/getByAccount")
    public JsonResult getByAccount(@NotNull(message = "ver.accountId.notNull") Integer accountId, Integer mapType, HttpServletRequest request) {
        if (mapType == null) {
            mapType = MapConstant.MAP_GOOGLE;
        }
        List<Geo> geoList = geoService.getByAccountId(accountId);
        return JsonResult.succ(geoList);
    }

}